import unittest

from instance import Instance, HasNameError


class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age


class TestInstance(unittest.TestCase):

    @classmethod
    def setUpClass(cls) -> None:
        cls.instance: Instance = Instance()
        cls.student1 = Student("1", 30)
        cls.student2 = Student("2", 30)
        # 制定名称
        cls.default_name = "default"
        cls.set_name = "set_name"

    def setUp(self) -> None:
        self.instance.set(self.default_name, self.student1)

    def tearDown(self) -> None:
        self.instance.clear()

    def test_set(self):
        try:
            self.instance.set(self.set_name, self.student2)
        except HasNameError as e:
            self.fail("设置数据失败")

        try:
            self.instance.set(self.set_name, self.student1)
            self.fail("未抛出必要的异常")
        except HasNameError as e:
            self.assertIsNotNone(e, "异常值为 None")

    def test_get(self):
        _tmp = self.instance.get(self.default_name)
        self.assertIs(_tmp, self.student1, "获取数据与原数据不同")

    def test_get_or_set(self):
        _tmp = self.instance.get_or_set(self.set_name, self.student2)
        self.assertIs(_tmp, self.student2, "获取数据与原数据不同")
        _tmp = self.instance.get_or_set(self.set_name, self.student1)
        self.assertIs(_tmp, self.student2, "获取数据与原数据不同")

    def test_get_or_set_func(self):
        def func1():
            return self.student2

        def func2():
            return self.student1

        _tmp = self.instance.get_or_set_func(self.set_name, func1)
        self.assertIs(_tmp, self.student2, "获取数据与原数据不同")
        _tmp = self.instance.get_or_set(self.set_name, func2)
        self.assertIs(_tmp, self.student2, "获取数据与原数据不同")

    def test_clear(self):
        self.instance.clear()
        self.assertIsNone(self.instance.get(self.default_name), "清空数据失败!")

    def test_clear_one(self):
        self.instance.set(self.set_name, self.student2)
        self.instance.clear_one(self.set_name)
        self.assertIsNone(self.instance.get(self.set_name), "删除一个数据失败!")
